use std::error::Error;
use std::net::TcpStream;
use std::io::{Read, Write};
use std::thread;
use icc_client::{IccParam, term_deal::term_req};

fn main() -> Result<(), Box<dyn Error>> 
{
    let file_path = "rs_param.json";
    let icc_param = IccParam::parse_and_build(file_path)?;

    // 创建 TCP 套接字并连接到指定的 IP 和端口
    let addr = format!("{}:{}", icc_param.ip, icc_param.ue_port);
    println!("Connecting to {}", addr);
    let mut stream = TcpStream::connect(&addr)?;
    let stream1 = stream.try_clone().expect("stream clone failed");

    thread::spawn(move || {
        ue_handler(stream1);
    });

    loop {
        let mut input = String::new();
        println!("请输入事件值, 1 ~ 21");
        std::io::stdin().read_line(&mut input)?;
        let event_value = input.trim().parse::<u32>().unwrap_or(1);
        let req = term_req::universal(event_value)?;
        stream.write_all(req.as_bytes())?;
        stream.flush()?;
    }

}

fn ue_handler(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    loop {
        buffer.fill(0);
        match stream.read(&mut buffer) {
            Ok(n) => {
                if n == 0 {
                    println!("Connection closed by peer");
                    break;
                }
                println!("tbx rec: {}", String::from_utf8_lossy(&buffer[..n]));
            }
            Err(e) => {
                println!("Error reading from stream: {}", e);
                break;
            }
        }
    }
}